<?php
App::uses('AdminbaseController', 'Controller');
class AdminmanageController extends AdminbaseController {

    public $layout = 'admin_content';
    public $user=array();   

    function beforeFilter() {
        parent::beforeFilter();
        $this->checkLogin(2); 
        $this->user = $this->getUser();   
        $this->set('userRoles',$this->user['roles']);
    }

    function index(){
        $this->admin_power('adminmanage_index',2);
        $this->loadModel('AdminUser');
        $params = $this->request->query;
        $conditions = array();
        if(!empty($params['keywords'])){ 
            $conditions["OR"]['email like'] = '%'.$params['keywords'].'%';
            $conditions["OR"]['user_name like'] = '%'.$params['keywords'].'%'; 
        }  
        $users = $this->AdminUser->find('all',array('conditions' => $conditions));  
        $this->set('dataList',$users);
    }

    //管理员添加/编辑
    function edit(){  
        $this->admin_power('adminmanage_edit',2);
        $params = $this->request->data;
        $uid = $this->request->query('id');   
        $this->loadModel('AdminUser');   
        $dataList=[];
        if($uid>0){ 
            $dataList = $this->AdminUser->findById($uid);  
            if(empty($dataList))
                $this->admin_redirect('/adminmanage/index',2,'管理员不存在！');
            $dataList=$dataList['AdminUser'];  
        }

        if($this->request->is('post') && $params['dosubmit']==1){  
            $params['status'] = isset($params['status'])?$params['status']:0; 
            if($params['utype']==1)  
                $params['roles'] = 'all';  
            else{
                $roleids = implode(",", $params['roles']);
                $params['roles'] = $roleids;
            }   
            if($uid>0) {
                $params['id'] = $uid; 
                if(!empty($params['password'])) 
                    $params['password']=md5($params['password'].$dataList['auth']); 
                else
                    unset($params['password']);  
            }
            else {
                $params['auth']=Ivf::random(8);
                if(empty($params['password'])) 
                    $params['password']='123456';  
                $params['password']=md5($params['password'].$params['auth']);  
            }
            $params['add_time']=date("Y-m-d H:i:s",time());
            unset($params['dosubmit'],$params['utype']);   
            if(!$this->AdminUser->save($params))  
                $this->admin_redirect('/adminmanage/index',2,'操作失败，请稍后再试');  
            if($uid>0){ 
                $this->adminLog($params['user_name'], 'edit', "管理员账户",$params);
            }   
            else
                $this->adminLog($params['user_name'], 'add', "管理员账户"); 
            $this->redirect("/adminmanage/index");     
        }     
        $this->loadModel('AdminGroup');  
        $groups = $this->AdminGroup->find('all'); 
        $this->set('roleList',$groups);
        $this->set('dataList',$dataList);
    }
    function roles(){
        $this->admin_power('adminmanage_roles',2);
        $this->loadModel('AdminGroup');  
        $groups = $this->AdminGroup->find('all'); 
        $this->set('roleList',$groups);
        $this->set('userId',$this->user['id']);
    }
 
    function roles_edit(){
        $this->admin_power('adminmanage_roles_edit',2);
        $params = $this->request->data;
        $roleid = $this->request->query('id');   
        $this->loadModel('AdminGroup');  
        $this->loadModel('AdminPermission');  
        $roleList=[];
        if($roleid>0){ 
            $roleList = $this->AdminGroup->findById($roleid);  
            if(empty($roleList))
                $this->admin_redirect('/adminmanage/roles',2,'无此角色！');
            $roleList=$roleList['AdminGroup'];
            //角色对应权限   
            $sources = $this->AdminPermission->findByGid($roleid);   
            if(!empty($sources['AdminPermission'])) 
                $roleList['sourceroleids']=json_decode($sources['AdminPermission']['action']);   
        }

        if($this->request->is('post') && $params['dosubmit']==1){   
            $attrRoles = $params['roles'];
            $data['gname'] = $params['role_name']; 
            $data['intro'] = $params['role_intro']; 
            $rid = isset($params['rid'])?intval($params['rid']):0; 
            if($rid>0) 
                $data['id'] = $rid;  
            $uptGroup=$this->AdminGroup->save($data);  
            if(!$uptGroup)  
                $this->admin_redirect('/adminmanage/roles',2,'操作失败，请稍后再试'); 
            if(!empty($params['roles'])){ 
                //角色对应权限   
                $sources = $this->AdminPermission->findByGid($uptGroup['AdminGroup']['id']); 
                if(!empty($sources['AdminPermission']))  
                    $data2['id']=$sources['AdminPermission']['id']; 
                //修改权限
                $data2['gid']=$uptGroup['AdminGroup']['id'];
                $data2['action']=json_encode($params['roles']);
                $this->AdminPermission->save($data2);
            }
            if($rid>0){
                $data['roles'] = $params['roles'];
                $this->adminLog($data['gname'], 'edit', "角色",$data);
            }   
            else
                $this->adminLog($data['gname'], 'add', "角色"); 
            $this->redirect("/adminmanage/roles");  
        }   
  
        $this->set('roleList',$roleList);
    }

    function logs(){
        $this->admin_power('adminmanage_logs',2);
        $this->loadModel('AdminLog');
        $params = $this->request->query;
        $conditions = array();
        if(!empty($params['keywords']))
            $conditions['log_info like'] = '%'.$params['keywords'].'%';  
        
        if(!empty($params['startTime'])){
            $startTime=date("Y-m-d 00:00:00",strtotime($params['startTime']));
            $conditions['log_time >= '] = $startTime;   
        }
        if(!empty($params['endTime'])){
            $endTime=date("Y-m-d 23:59:59",strtotime($params['endTime']));
            $conditions['log_time <= '] = $endTime;   
        }  
        $this->paginate = array('conditions' => $conditions,'order'=>array('id desc'),'limit' => 10);
        try {
            $users = $this->paginate('AdminLog'); 
        } catch (NotFoundException $e) {
            $users = array();
        } 
        $this->set('dataList',$users);
    }

    function uptpwd(){
        $params = $this->request->data; 
        $this->loadModel('AdminUser'); 
        if($this->request->is('post') && $params['dosubmit']==1){   
            $oldpassword = $params['password'];
            $newpassword = $params['Nes_pas'];
 
            $adminInfo = $this->AdminUser->findById($this->user['id']); 
            if($adminInfo['AdminUser']['password'] != md5($oldpassword.$adminInfo['AdminUser']['auth'])){ 
                $this->ajaxReturn(4001, '原密码错误，请重新输入'); 
            }  
            $data=[];
            $data['password']=md5($newpassword.$adminInfo['AdminUser']['auth']);
            $data['id']=$this->user['id'];
            if(!$this->AdminUser->save($data)){ 
                $this->ajaxReturn(4002, '修改失败！'); 
            } 
            $this->ajaxReturn(200, '修改成功！');  
        } 
        $this->set('userInfo',$this->user);
    } 
}